import React, { useEffect, useState } from 'react'
import './SiderMenu.css'

import { useNavigate, useLocation } from 'react-router-dom'
import { connect } from 'react-redux'
import { reflushIndex } from '../../redux/actionCreator/IndexActionCreater'
//import axios from 'axios'
import { Layout, Menu } from 'antd'
import axios from 'axios'


// 将sider解构出来
const { Sider } = Layout





// 侧边栏组件，将采用动态渲染的方式
function SiderMenu (props) {

  // 编程式跳转
  const navigate = useNavigate()
  const { reflushIndex, flush } = props
  // 使用 hook
  const location = useLocation()
  const { from, pathname } = location
  //console.log(pathname)
  // 假设列表的数据
  const menuListData = []

  const [menus, setMenus] = useState([])


  const renderMenus = (menuList) => {

    menuListData.push({

      onClick: () => {
        navigate("/index/index")
      },
      key: '/index',
      // 图标
      label: "首页",
    })

    menuList.map((item) => {

      if (item.children === undefined) {


        item.onClick = () => {
          navigate(item.key)
        }
      } else {
        item.children.map((t) => {
          t.onClick = () => {
            navigate(t.key)
          }
          return t
        })
      }
      menuListData.push(item)
      return item
    })

    return menuListData
  }


  useEffect(() => {
    axios.get("http://localhost:8081/sideMenus/getSideMenus",
      {
        params: {
          username: localStorage.getItem("username"),
        },
        headers: {
          satoken: localStorage.getItem("satoken")
        }
      }
    ).then(r => {
      //console.log(r)
      if (r.data.code === 200) {
        setMenus(r.data.data)
      } else {
        navigate("/login")
      }
    })
  }, [flush])




  let heightLight = []
  // 每次选中一个标签后，此标签高亮并记录key值，当页面刷新后还停留在此标签
  if (pathname === '/index/index') {
    heightLight = ['/index']
  } else {
    heightLight = [pathname]
  }
  const openKeys = ["/" + pathname.split("/")[2]]

  return (
    // 侧边栏collapsible为可折叠collapsed={false}为不折叠，true为折叠
    <Sider theme="light" trigger={null} collapsible collapsed={false}>
      {/* 此处的样式使得侧边栏内容过多时局部滚动 */}
      <div style={{ display: 'flex', height: '100%', 'flexDirection': 'column' }}>
        {/* 标题 */}
        <div className="logo" >协同办公系统</div>


        <div style={{ flex: 1, 'overflow': 'auto' }}>
          <Menu
            theme="light"
            mode="inline"
            // 默认高亮的按钮，用唯一的key来标记
            selectedKeys={heightLight}
            // 默认打开折叠的标签,是一级路径
            defaultOpenKeys={openKeys}
            // 列表设置值
            items={renderMenus(menus)}
          />
        </div>
      </div>
    </Sider>


  )
}


// 获取公共状态
const mapStateToProps = (state) => {
  return {
    flush: state.IndexReducer.reflus
  }
}

// 修改公共状态的方法
const mapDispatchToProps = {
  reflushIndex
}
export default connect(mapStateToProps, mapDispatchToProps)(SiderMenu)